//
//  NSCalendar+time.m
//  日历类使用
//
//  Created by 刘璇 on 2017/10/29.
//  Copyright © 2017年 Xuan. All rights reserved.
//

#import "NSCalendar+time.h"

@implementation NSCalendar (time)


#pragma mark ----------------------------
#pragma mark 获取当前月份有多少天:

+(NSInteger)getDaysWithData:(NSDate *)date{
    // 创建一个日期类对象(当前月的calendar对象)
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // NSRange是一个结构体，其中location是一个以0为开始的index，length是表示对象的长度。他们都是NSUInteger类型。
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    NSUInteger numberOfDaysInMonth = range.length;
    return numberOfDaysInMonth;
}
#pragma mark ----------------------------
#pragma mark获取目标月份的天数:

+(NSInteger)getNextNMonthForDays:(NSDate*)date
{
    NSCalendar * calendar = [NSCalendar currentCalendar];
    // 调用rangeOfUnit方法:(返回一样是一个结构体)两个参数一个大单位，一个小单位(.length就是天数，.location就是月)
    NSInteger monthNum = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date].length;
    return monthNum;
}
#pragma mark ----------------------------
#pragma mark 获取一个目标date(包含某个月的1号数据)，或者说获取某个月的1号的date对象

+(NSDate *)getAMonthframDate:(NSDate*)date {
    NSCalendar * calendar = [NSCalendar currentCalendar];
    // 指定日历单位，如日期和月份。(这里指定了年月日，还有其他字段添加单位.特别齐全 ：世纪，年月日时分秒等等等)
    NSCalendarUnit dayInfoUnits  = NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    // NSDateComponents封装了日期的组件,年月日时分秒等(个人感觉像是平时用的model模型)
    NSDateComponents *components = [calendar components: dayInfoUnits fromDate:date];
    // 指定1号
    components.day = 1;
    // 指定月份(我这里是获取当前月份的下1个月的1号的date对象,所以用的++，其上个月或者其他同理)
    components.month++;
    // 转成需要的date对象return
    NSDate * nextMonthDate =[calendar dateFromComponents:components];
    return nextMonthDate;
}

#pragma mark ----------------------------
#pragma mark获取某个月的1号是星期几(必不可少的一个方法，用来布局UI使每月1号与星期队形起来):

+(NSInteger)getFirstDayWeekForMonth:(NSDate*)date
{
    // NSCalendarIdentifierGregorian : 指定日历的算法
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // NSDateComponents封装了日期的组件,年月日时分秒等(个人感觉像是平时用的model模型)
    // 调用NSCalendar的components:fromDate:方法返回一个NSDateComponents对象
    // 需要的参数分别components:所需要的日期单位 date:目标月份的date对象
    NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:date];
    // 直接调用自己weekDay属性
    NSInteger weekday = [comps weekday];
#warning mark --找了很多原因不知道为什么星期数总是比实际快一天,有时间找更好的解决方法（暂时用-1天处理了）
    weekday--;
    if (weekday == 7) {
        return 0;
    }else return weekday;
}
#pragma mark ----------------------------
#pragma mark当前时间与之前时间的间隔:

/**
 *  @author jaki, 15-09-21 17:09:42
 *  @brief  获取一个标准时间戳与当前时间的时间差
 *  @param interval 时间戳
 *  @return 距离当前时间的时间间隔
 */
-(NSString *)getStandardTimeInterval:(NSTimeInterval)interval{
    //进行时间差比较
    //当前时间与1970时间戳(秒为单位)
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    // 当前时间戳-当时时间戳=差值(比如朋友圈动态发表时间为10分钟前(当前时间-发表时间))
    NSTimeInterval timeInterval = time-interval;
    //计算出天、小时、分钟
    int day = timeInterval/(60*60*24);
    int hour = ((long)timeInterval%(60*60*24))/(60*60);
    int minite = ((long)timeInterval%(60*60*24))%(60*60)/60;
    NSMutableString * timeStr = [[NSMutableString alloc]init];
    // 逻辑判断
    if (day!=0) {
        [timeStr appendString:[NSString stringWithFormat:@"%d天前",day]];
    }else{
        if (hour!=0) {
            [timeStr appendString:[NSString stringWithFormat:@"%d小时前",hour]];
        }else{
            if (minite<1) {
                [timeStr appendString:@"刚刚"];
            }else{
                [timeStr appendString:[NSString stringWithFormat:@"%d分钟前",minite]];
            }
        }
    }
    return timeStr;
}
#pragma mark ----------------------------
#pragma mark  获取当前系统时间:

+(NSString *)getCurrentTime{
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    // 格式化系统时间字符串</code>
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString * time = [formatter stringFromDate:[NSDate date]];
    return time;
}
#pragma mark ----------------------------
#pragma mark 返回年月日时分秒：

//-(int)getYear{
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:self];
//    return (int)dateComponent.year;
//
//}
//-(int)getMonth{
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags =  NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:self];
//    return (int)dateComponent.month;
//}
//-(int)getDay{
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags =  NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:self];
//    return (int)dateComponent.day;
//}
//-(int)getHour{
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags =  NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:self];
//    return (int)dateComponent.hour;
//}
//-(int)getMinute{
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags =  NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:self];
//    return (int)dateComponent.minute;
//}
//-(int)getSecond{
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags =  NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
//    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:self];
//    return (int)dateComponent.second;
//}
#pragma mark ----------------------------
#pragma mark  date对象NSString互相转换:

// date对象转换成字符串（最后return根据自己需求处理）
+(NSString * )theTargetDateConversionStr:(NSDate * )date withFormatter:(NSString *)formatter
{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:formatter];//设定时间格式,这里可以设置成自己需要的格式
    NSString *currentDateStr = [dateFormat stringFromDate:date];
    // 根据自己需求处理字符串
    return currentDateStr;
}
// NSString对象转date
+(NSDate* )theTargetStringConversionDate:(NSString *)str withFormatter:(NSString *)formatter
{
    //设置转换格式
    NSDateFormatter *format= [[NSDateFormatter alloc] init] ;
    [format setDateFormat:formatter];
    NSDate *date=[format dateFromString:str];
    return date;
}

+(NSString *)todayBeginTimeWithDate:(NSDate *)date{
    NSString * time = [[NSCalendar theTargetDateConversionStr:date withFormatter:@"yyyy-MM-dd"] stringByAppendingString:@" 00:00:00"];
    NSDate * dates = [NSCalendar theTargetStringConversionDate:time withFormatter:@"yyyy-MM-dd 00:00:00"];

    return [Factory timeStampFromDate:dates];
}

#pragma mark ----------------------------
#pragma mark 获取距离某一月的几个月的日期
+(NSDate *)getAnyMonthDataWithData:(NSDate *)date month:(NSInteger)month
{
    NSDateFormatter * forMatter = [[NSDateFormatter alloc]init];
    [forMatter setDateFormat:@"yyyy-MM-dd"];
    NSString * dateStr = [forMatter stringFromDate:date];
    //获取 年月日
    NSInteger year = [[dateStr substringToIndex:4] integerValue];
    NSInteger Month = [[dateStr substringWithRange:NSMakeRange(5, 2)] integerValue];
    
    NSInteger newMonth = Month + month;
    
    while (newMonth <= 0) {
        year--;
        newMonth += 12;
    }
    while (newMonth > 12) {
        year ++;
        newMonth -= 12;
    }
    
    NSString *  newStr = [NSString stringWithFormat:@"%ld-%ld-%d",(long)year,(long)newMonth,1];
    
    return [NSCalendar theTargetStringConversionDate:newStr withFormatter:@"yyyy-MM-1"];
}

+(int)compareDate:(NSDate *)date01{
    
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"yyyy-MM-dd"];
    NSString *dt1 = [df stringFromDate:date01];
    NSString *dt2 = [df stringFromDate:[NSDate date]];
    
    NSDate * d1 = [NSCalendar theTargetStringConversionDate:dt1 withFormatter:@"yyyy-MM-dd"];
    NSDate * d2 = [NSCalendar theTargetStringConversionDate:dt2 withFormatter:@"yyyy-MM-dd"];
    
    return [d1 timeIntervalSinceDate:d2] / 60 / 60 / 24;
}
@end
